package com.zsc.newbuds.service.impl;

import com.zsc.newbuds.entity.Admin;
import com.zsc.newbuds.entity.Application;
import com.zsc.newbuds.mapper.ApplicationMapper;
import com.zsc.newbuds.service.ApplicationService;
import com.zsc.newbuds.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author D
 */
@Service
public class ApplicationServiceImpl implements ApplicationService {

    @Autowired
    ApplicationMapper applicationMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public List<Application> getApplicationList() {

        List<Application> applicationList = new ArrayList<Application>();
        String key = "list:applicationList";
        if(redisUtil.hasKey(key)){
            System.out.println("从redis中获取pplication");
            Map<Object, Object> map = redisUtil.hmget(key);
            for(Map.Entry<Object, Object> ap:map.entrySet()){
                Application application = (Application) ap.getValue();
                applicationList.add(application);
            }
        }else {
            System.out.println("数据库获取Application");
            Map< String,Object> map = new HashMap<>();
            applicationList = applicationMapper.getApplicationList();
            for (Application application : applicationList){
                map.put(application.getApplicationId().toString(),application);
            }
            redisUtil.hmset(key,map);
        }
        return applicationList;
    }

    @Override
    public void updateState(Integer id, String state) {
        String key = "list:applicationList";
        if(redisUtil.hasKey(key)){
            Application application = (Application) redisUtil.hget(key,id.toString());
            application.setApplicationState(state);
            redisUtil.hset(key,id.toString(),application);
        }else {
            applicationMapper.updateState(id, state);
        }
    }
}
